package com.kerong.chedeli.view.tenant;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import com.google.gson.Gson;

import com.kerong.chedeli.CheDeLiApplication;
import com.kerong.chedeli.R;
import com.kerong.chedeli.data.modal.CarInfoModal;
import com.kerong.chedeli.data.modal.CarSimpleModal;
import com.kerong.chedeli.data.modal.PriceModal;
import com.kerong.chedeli.data.modal.ResultModal;
import com.kerong.chedeli.view.BaseActivity;
import com.kerong.chedeli.view.UIHelper;
import com.kerong.chedeli.widget.TimePicker;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.DatePicker;
import android.widget.ImageView;
import android.widget.TextView;
import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import net.tsz.afinal.FinalBitmap;
import net.tsz.afinal.FinalHttp;
import net.tsz.afinal.http.AjaxCallBack;
import net.tsz.afinal.http.AjaxParams;

/**
 * 提交订单 Created by LiYaoHua on 2015/10/7.
 */
public class GetOrderActivity extends BaseActivity {
    @Bind(R.id.toolbar)
    Toolbar toolbar;
    @Bind(R.id.iv_car_photo)
    ImageView iv_car_photo;
    @Bind(R.id.tv_vin)
    TextView tv_vin;
    @Bind(R.id.tv_car_name)
    TextView tv_car_name;
    @Bind(R.id.tv_starttime)
    TextView tv_starttime;
    @Bind(R.id.tv_endtime)
    TextView tv_endtime;
    @Bind(R.id.tv_time)
    TextView tv_time;
    @Bind(R.id.tv_rent)
    TextView tv_rent;
    @Bind(R.id.tv_getcaraddress)
    TextView tv_getcaraddress;

    FinalBitmap finalBitmap = null;
    private String carid;
    private String usrmobile;
    private CarSimpleModal carSimple;
    private Calendar startCalendar;
    private Calendar endCalendar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_get_order);
        ButterKnife.bind(this);
        finalBitmap = FinalBitmap.create(this);
        initToolBar(toolbar);
        init();
    }

    private void init() {
        carSimple = this.getIntent().getExtras().getParcelable("carSimple");
        carid = this.getIntent().getExtras().getString("carid");
        usrmobile = this.getIntent().getExtras().getString("usrmobile");
        finalBitmap.display(iv_car_photo, carSimple.getCoverphoto());
        startCalendar = Calendar.getInstance();
        endCalendar = Calendar.getInstance();
        tv_starttime.setText(getTimeString(startCalendar));
        tv_endtime.setText(getTimeString(endCalendar));
        tv_vin.setText(carSimple.getVin());
        tv_car_name.setText(carSimple.getBrand_name());
        tv_time.setText(getTimeJiange(endCalendar, startCalendar));
        tv_getcaraddress.setText(carSimple.getAddress());

    }

    @OnClick(R.id.tv_starttime)
    public void OnStartTimeClick() {
        setTime(1);
    }

    @OnClick(R.id.tv_endtime)
    public void OnEndTimeClick() {
        setTime(2);
    }

    @OnClick(R.id.bt_submit_order)
    public void OnSubmitClick() {
        if (startCalendar.after(endCalendar)) {
            UIHelper.showMessage("时间选择错误");
            return;
        } else {
            AjaxParams params = new AjaxParams();
            params.put("usrmobile", usrmobile);
            params.put("carid", carid);
            params.put("taketime", getTimeString(startCalendar));
            params.put("backtime", getTimeString(endCalendar));
            String url ="http://cdlmapi.0371e.cn/v1/postorder";
            FinalHttp finalHttp = new FinalHttp();
            finalHttp.configCookieStore(CheDeLiApplication.cookieStore);
            finalHttp.get(url, params, new AjaxCallBack<String>() {
                @Override
                public void onSuccess(String s) {
                    try {
                        ResultModal resultModal = new Gson().fromJson(s,ResultModal.class);
                        if(resultModal.getStatus() == 0){
                            UIHelper.showMessage("订单提交成功");
                            finish();
                        }else{
                            UIHelper.showMessage(resultModal.getMessage());
                        }
                    }catch (Exception e){
                        UIHelper.showMessage("订单提交失败");
                    }
                }

                @Override
                public void onFailure(Throwable t, int errorNo, String strMsg) {
                   UIHelper.showMessage("订单提交失败");
                }
            });
        }
    }

    public void setTime(final int index) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        View view = View.inflate(this, R.layout.time_dialog, null);
        final DatePicker datePicker = (DatePicker) view.findViewById(R.id.date_picker);
        final TimePicker timePicker = (TimePicker) view.findViewById(R.id.time_picker);
        builder.setView(view);

        Calendar cal = Calendar.getInstance();
        cal.setTimeInMillis(System.currentTimeMillis());
        datePicker.init(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH), null);

        timePicker.setIs24HourView(true);
        timePicker.setCurrentHour(cal.get(Calendar.HOUR_OF_DAY));
        timePicker.setCurrentMinute(cal.get(Calendar.MINUTE));
        timePicker.setCurrentSecond(cal.get(Calendar.SECOND));

        builder.setTitle("选取时间");
        builder.setPositiveButton("确  定", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {

                Calendar calendar = Calendar.getInstance();
                calendar.set(Calendar.YEAR, datePicker.getYear());
                calendar.set(Calendar.MONTH, datePicker.getMonth());
                calendar.set(Calendar.DAY_OF_MONTH, datePicker.getDayOfMonth());
                calendar.set(Calendar.HOUR_OF_DAY, timePicker.getCurrentHour());
                calendar.set(Calendar.MINUTE, timePicker.getCurrentMinute());
                calendar.set(Calendar.SECOND, timePicker.getCurrentSeconds());
                if (index == 1) {
                    startCalendar = calendar;
                    tv_starttime.setText(getTimeString(startCalendar));
                    tv_time.setText(getTimeJiange(endCalendar, startCalendar));
                    tv_rent.setText(getRent(endCalendar, startCalendar));
                } else if (index == 2) {
                    endCalendar = calendar;
                    tv_endtime.setText(getTimeString(endCalendar));
                    tv_time.setText(getTimeJiange(endCalendar, startCalendar));
                    tv_rent.setText(getRent(endCalendar, startCalendar));

                }
                dialog.cancel();
            }
        });
        Dialog dialog = builder.create();
        dialog.show();
    }

    public String getTimeString(Calendar calendar) {
        long timelong = calendar.getTimeInMillis();
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        return df.format(new Date(timelong));
    }

    public String getTimeJiange(Calendar calendarEnd, Calendar calendarStart) {
        if (calendarStart.after(calendarEnd)) {
            return "选取时间错误";
        } else {
            long seconds = (calendarEnd.getTimeInMillis() - calendarStart.getTimeInMillis()) / 1000;
            long day = seconds / (3600 * 24);
            seconds = seconds % (3600 * 24);
            long hour = seconds / 3600;
            seconds = seconds % 3600;
            long minute = seconds / 60;
            return day + "天" + hour + "小时" + minute + "分钟";
        }
    }

    public String getRent(Calendar calendarEnd, Calendar calendarStart) {
        if (carSimple != null) {
            PriceModal price = carSimple.getPrices();
            if (calendarStart.after(calendarEnd)) {
                return "";
            } else {
                long seconds = (calendarEnd.getTimeInMillis() - calendarStart.getTimeInMillis()) / 1000;
                long day = seconds / (3600 * 24);
                seconds = seconds % (3600 * 24);
                long hour = seconds / 3600;
                seconds = seconds % 3600;
                long minute = seconds / 60;
                double rent = Double.parseDouble(price.getDay()) * day + Double.parseDouble(price.getHour()) * hour
                        + Double.parseDouble(price.getMinute()) * minute;
                DecimalFormat df = new DecimalFormat("0.00");
                return df.format(rent) + "元";
            }
        } else {
            return "";
        }
    }
}
